#include <stdio.h>
#include "knuth_stack.h"

int main(void)
{stack ptr = create(), merge = create();
 int i, numbs, data, prev = 0, temp_1, temp_2;
 printf("How many elements contains first team of sorted nubers?\n");
 scanf("%d", &numbs);							/*I read the number of the elements will be given*/
 if( numbs < 0 ){
	fprintf(stderr,"Please, give a number larger or equal to 0\n");
	return 1;
	}
 printf("Please, type the number(s)\n");
 for(i = 0;i < numbs; i++, prev=data){					/*I read the numbers*/
	scanf("%d",&data);
	if(prev > data){
		fprintf(stderr,"The numbers must be sorted!!!\n");
		return 1;
		}		
	if( push(ptr,data,left_stack) == false ){			/*I push the data in the left stack*/
		fprintf(stderr,"Stack overflowed!!!\n"); 
		return 1;
		}
	}
 printf("How many elements contains second team of sorted numbers?\n"); /*I read the number of the element will be given*/
 scanf("%d",&numbs);
  if( numbs < 0 ){
	fprintf(stderr,"Please, give a nubmer larger or equal to 0\n");
	return 1;
	}
 prev=0;
 if(full(ptr) == true){
	fprintf(stderr,"Stack overflowed!!!\n");
	return 1;
	}
 printf("Please, type the number(s)\n");	
 for(i = 0;i < numbs;i++, prev = data){					/*I read the numbers*/
	scanf("%d",&data);
	if(prev > data){
		fprintf(stderr,"The numbers must be sorted!!!\n");
		return 1;
		}
	if( push(ptr,data,right_stack) == false){			/*I push the data in the right stack*/
		fprintf(stderr,"Stack overflowed!!!\n");
		return 1;
		}
	}
 while( empty(ptr,left_stack) == false && empty(ptr,right_stack) == false){
	pop(ptr,&temp_1,left_stack);						/*I pop the elements from the stacks to compare them*/
	pop(ptr,&temp_2,right_stack);
	if(temp_1 < temp_2){	
		push(merge,temp_2,left_stack);					/*I push the bigger in the merge stack*/
		push(ptr,temp_1,left_stack);					/*I push the other in its initial stack*/
		}
	else{
		push(merge,temp_1,left_stack);
		push(ptr,temp_2,right_stack);
		}
	}
 if( empty(ptr,left_stack) == true){				/*I move all the elements from the non empty stack to the merge stack*/
	while(empty(ptr,right_stack) ==false ){
		pop(ptr,&data,right_stack);
		push(merge,data,left_stack);
		}
	}	
 else{
	while(empty(ptr,left_stack) == false){
		pop(ptr,&data,left_stack);
		push(merge,data,left_stack);
		}
	}

 while(empty(merge,left_stack) == false){		/*I pop and print the merge stack*/
	pop(merge,&data,left_stack);
	printf("%d ",data);
	}
 printf("\nElements sorted!!!\n");
 return 0;
}
